package com.segersten.othello.model;

import com.google.common.base.Function;

public class BoardScoreFunction implements Function<Brick, Integer>
{
    private int scoreSum = 0;
    private Color positiveColor;
    private int size;

    public BoardScoreFunction(Color positiveColor, int size)
    {
        this.positiveColor = positiveColor;
        this.size = size;
    }

    @Override
    public Integer apply(Brick brick)
    {
        int score = calcScore(brick);
        scoreSum+=score;
        return score;
    }

    public int getScoreSum()
    {
        return scoreSum;
    }
    
    private int calcScore(Brick brick)
    {
        Point point = brick.getPoint();
        if (isCornerBrick(point))
        {
            return brick.getColor().equals(positiveColor) ? 8 : -8;
        }
        if (isBorderBrick(point))
        {
            return brick.getColor().equals(positiveColor) ? 4 : -4;
        }
        if (isNextToBorderBrick(point))
        {
            return brick.getColor().equals(positiveColor) ? 1 : -1;
        }
        if (isBrick(brick))
        {
            return brick.getColor().equals(positiveColor) ? 2 : -2;
        }
        throw new IllegalStateException("No brick at this point - " + brick);
    }

    private boolean isBrick(Brick brick)
    {
        return brick!=null && brick.isPass()==false;
    }

    private boolean isNextToBorderBrick(Point point)
    {
        return point.getX() == 1 || point.getX() == size - 2 || point.getY() == 1 || point.getY() == size - 2;
    }

    private boolean isBorderBrick(Point point)
    {
        return point.getX() == 0 || point.getX() == size - 1 || point.getY() == 0 || point.getY() == size - 1;
    }

    private boolean isCornerBrick(Point point)
    {
        return (point.getX() == 0 && point.getY() == 0) || (point.getX() == size - 1 && point.getY() == 0) || (point.getX() == 0 && point.getY() == size - 1)
                || (point.getX() == size - 1 && point.getY() == size - 1);
    }

}
